package com.usdt.system.service.impl.cp;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.usdt.common.core.redis.RedisClient;
import com.usdt.common.exception.ServiceException;
import com.usdt.system.service.cp.RequestManageService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RequestManageServiceImpl implements RequestManageService {
	
	private final String AUTHORIZATION_KEY = "SYS:AUTHORIZATION:TOKEN";
	
	private final String OAUTH_PATH = "/oauth2/client_token";
	
	@Value("${sys.properties.request.url_path}")
	public String urlPath;
	
	@Value("${sys.properties.request.client_id}")
	public String clientId;
	
	@Value("${sys.properties.request.client_secret}")
	public String clientSecret;

	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private RedisClient redisClient;
	
	private String getAuthorization() {
		//String authorization = (String)redisTemplate.opsForValue().get(AUTHORIZATION_KEY);
		//String authorization = (String)redisClient.get(AUTHORIZATION_KEY);
		String authorization = null;
		if(StringUtils.isBlank(authorization)) {
			// 请求头
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.set("Connection", "Keep-Alive");
			headers.add("user-agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
			HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);

			String url = urlPath + OAUTH_PATH +"?grant_type=client_credentials&client_id="+clientId+"&client_secret="+clientSecret;
			ResponseEntity<String> exchange = restTemplate.exchange(
					url, 
					HttpMethod.GET, // 请求方法
					httpEntity, // 包含请求头的HttpEntity
					String.class // 响应类型
			);
			if (null == exchange) {
				throw new ServiceException("获取authorization失败", -1);
			}
			 String body = exchange.getBody();
			 log.info("获取oauth2认证信息返回："+body);
			 JSONObject object = JSON.parseObject(body);
			 JSONObject data = object.getJSONObject("data");
			 if (null == data) {
					throw new ServiceException("获取authorization失败", -1);
				}
			 JSONObject data1 = data.getJSONObject("data");
			 if (null == data1) {
					throw new ServiceException("获取authorization失败", -1);
				}
			 authorization = data1.getString("client_token");
			 Long expiresIn = data1.getLong("expires_in");
			 //缓存
			 //redisClient.set(AUTHORIZATION_KEY, authorization, (expiresIn - 3600)>0?(expiresIn - 3600):1);
		}
		
		return authorization;
	}

	@Override
	public <T> T getMethod(String path, Class<T> responseType) {
		log.info("get请求cp接口："+path);
		// 请求头
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Connection", "Keep-Alive");
		//headers.set("Authorization", getAuthorization());
		headers.add("user-agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
		HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);

		ResponseEntity<T> exchange = restTemplate.exchange(
				urlPath+path, 
				HttpMethod.GET, // 请求方法
				httpEntity, // 包含请求头的HttpEntity
				responseType // 响应类型
		);
		if (null == exchange) {
			throw new ServiceException("请求失败", -1);
		}
		//log.info("get请求cp接口返回返回："+exchange.getBody().toString());
		return exchange.getBody();
	}

	@Override
	public <T> T postMethod(String path, Map<String, Object> params, Class<T> responseType) {
		log.info("post请求cp接口："+path+",请求参数："+params);
		// 请求头
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Connection", "Keep-Alive");
		//headers.set("Authorization", getAuthorization());
		headers.add("user-agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
		HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), headers);

		ResponseEntity<T> exchange = restTemplate.exchange(
				urlPath+path, 
				HttpMethod.POST, // 请求方法
				httpEntity, // 包含请求头的HttpEntity
				responseType // 响应类型
		);
		if (null == exchange) {
			throw new ServiceException("请求失败", -1);
		}
		//log.info("post请求cp接口返回返回："+exchange.getBody().toString());
		return exchange.getBody();
	}

	public static void main(String[] args) {
		log.info("post请求cp接口：{}");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("123", "123");
		
		System.out.println(params);
	}
}
